package com.rdtravel.converters;

import com.rdtravel.entities.Customer;
import com.rdtravel.services.CustomersService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;

public class StringToCustomerConverter implements Converter<String, Customer> {
	private final CustomersService customersService;

	@Autowired
	public StringToCustomerConverter(CustomersService customersService) {
		this.customersService = customersService;
	}

	@Override
	public Customer convert(String idOrUsername) {
		if (idOrUsername == null || idOrUsername.isEmpty()) {
			return null;
		}
		try {
			return customersService.findById(Long.parseLong(idOrUsername));
		} catch (NumberFormatException ex) {
			return customersService.findByUsername(idOrUsername);
		}
	}

}
